package com.gitee.feizns.web.utils;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author feizns
 * @since 2019/7/13
 */
public abstract class FileUtils {

    private static final int DEFAULT_BUFF_SIZE = 10240;

    public static final String getSuffix(String filename) {
        int index = -1;
        return filename != null && (index = filename.lastIndexOf(".")) != -1
                ? filename.substring(index)
                : null;
    }

    /**
     * 写入
     */
    private static final void write(InputStream is, File file) throws IOException {
        try ( FileOutputStream fos = new FileOutputStream(file) ) {
            IOUtils.transfer(is, fos);
        }
    }

    /**
     * 写入多个文件
     */
    public static final void writer(InputStream is, File... files) throws IOException {
        InputStream[] streams = IOUtils.clone(is, files.length);
        for (int i = 0; i < files.length; i++) {
            write(streams[i], createDir(files[i]));
        }
    }

    /**
     * 创建文件
     * @param file
     * @return
     */
    public static final File createDir(File file) {
        if ( file.exists() == false ) {
            if ( file.isDirectory() )
                file.mkdirs();
            else if ( file.getParentFile() != null )
                file.getParentFile().mkdirs();
        }
        return file;
    }

    /**
     * 关闭流
     * @param closeables
     * @throws IOException
     */
    public static final void close(Closeable... closeables) throws IOException {
        for (Closeable closeable : closeables)
            closeable.close();
    }

}
